package com.fafian.publish.json;

import java.util.LinkedHashSet;
import java.util.Set;

import com.fafian.publish.NoListenerException;
import com.fafian.publish.PublishBus;
import com.fafian.publish.SynchronousBus;
import com.fafian.publish.SynchronousBusException;

public class JSONStringBus {

	protected static final String BASE_NAME="JSONService-BUS";
	private Set<String> supportedUris;
	
	private SynchronousBus<String, String> internalBus;
	
	public JSONStringBus(PublishBus bus) {
		internalBus = new SynchronousBus<String,String>(bus);
		supportedUris = new LinkedHashSet<String>();
	}
	
	public String getResponse(String uri, String request) throws SynchronousBusException, NoListenerException{
		String uriToPass = uri;
		if (!supportedUris.contains(uri)){
			boolean error = true;
			for (String checkUri: supportedUris){
				if (uri.startsWith(checkUri)){
					uriToPass = checkUri;
					error = false;
				}
			}
			if (error){
				throw new NoListenerException();
			}
		}
		return internalBus.publish(BASE_NAME+"-"+uriToPass, request);
	}
	
	public synchronized <S,T>void registerWorker(JSONAbstractSynchronousWorker<S,T> worker){
		supportedUris.add(worker.getUri());
		internalBus.registerWorker(worker);
	}
	

}
